<?php
namespace app\admin\controller;
\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);
use app\admin\Controller;
use think\console\output\Question;
use think\Db;
use think\Config;
use think\Loader;
/**
 * 题目控制器
 * 题目列表 增删改查题目 
 * Time: 上午 9:19
 */
class Questions extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];
    protected $model;

    public function __construct()
    {
        parent::__construct();
        //根据btype 获取相应的model
        $bankType = $this->request->param('btype');
        $this->model = $bankType==1 ? $this->getModel('question_db'):  $this->getModel('questions') ;
    }

    protected function filter(&$map)
    {
        if ($this->request->param("id")) {
            $map['id'] = ["like", "%" . $this->request->param("id") . "%"];
        }
        if ($this->request->param("q_question")) {
            $map['question'] = ["like", "%" . $this->request->param("q_question") . "%"];
        }
        if ($this->request->param("q_create_time")) {
            $map['create_time'] = ["like", "%" . $this->request->param("q_create_time") . "%"];
        }
		
		if($this->request->param("p_name")){
            $map['q_question'] = ["like", "%" . trim($this->request->param("p_name")) . "%"];
        }
		
		if($this->request->param("p_status")){
            $map['status'] = ["=", (int)$this->request->param("p_status")];
        }

		
    }

    /**
     * 禁用限制
     */
    protected function beforeForbid()
    {
        //禁止禁用Admin模块,权限设置节点
        $this->filterId([1, 2], '该分组不能被禁用');
    }
    /**
     * 删除限制
     */
    protected function beforeDelete()
    {
        //禁止删除Admin模块,权限设置节点
        $this->filterId([1, 2], '该分组不能被删除');
    }
    /**
     * 永久删除限制
     */
    protected function beforeForeverDelete()
    {
        //禁止删除Admin模块,权限设置节点
        $this->filterId([1, 2], '该分组不能被删除');
    }
    /**
     * 首页
     * @return mixed
     */
    public function index()
    {

        $bankId = $this->request->param('bankid');
        $bankType = $this->request->param('btype');
      //  $child_plaform = getChildAdminRegByPlaformId($this->plaform);
		$child_plaform = $_SESSION["think"]["reg"];
		$child_plaforms = [$child_plaform];
        // 列表过滤器，生成查询Map对象
		
		$QbankAssociation = new \app\common\model\QbankAssociation();
		$qbank_adminreg = $QbankAssociation->getAdminReg($this->plaform,$bankId);
		$qbank_type = 1;
		if($qbank_adminreg){
			$child_plaforms[] = $qbank_adminreg;
			$qbank_type = 0;
		}
		/**修复无法查看分题库问题**/
		$qbank_parentid = Db::name('qbank')->field('parentid')->where(['id'=>$bankId])->find();
		if($qbank_parentid['parentid']){
			$mode = $model = $this->getModel('QuestionDb');
			$map = $this->search($mode, [$this->fieldIsDelete => $this::$isdelete]);
		} else {
			$mode = $model = $this->getModel();
            # ,$this->fieldReg => ['in',$child_plaforms] # 权限相关
			$map = $this->search($mode, [$this->fieldIsDelete => $this::$isdelete]);
		}
		/**修复无法查看分题库问题 end**/
       // $map = $this->search($mode, [$this->fieldIsDelete => $this::$isdelete,$this->fieldReg => ['in',$child_plaforms]]);
        if(!empty($bankId)) $map['q_qbankid'] = $bankId;

        //更具题型筛选
        $qbankids = $this->request->param("qbankid");
        if(isset($qbankids) && $qbankids!=0){
            // var_dump($qbankids);
            $map['q_typeid'] = $qbankids;
        }
		
		if($this->request->param("levels")){
            $map['q_level'] = ["=", (int)$this->request->param("levels")];
        }
		
        //更具知识点赛选
        $getqbankid = $this->request->param("knowstypeid");
        if(isset($getqbankid) && $getqbankid!=0){
            $map['q_knowsid'] = $getqbankid;   
        }
        // 特殊过滤器，后缀是方法名的
        $actionFilter = 'filter' . $this->request->action();
        if (method_exists($this, $actionFilter)) {
            $this->$actionFilter($map);
        }

        // 自定义过滤器
        if (method_exists($this, 'filter')) {
            $this->filter($map);
        }
		
		$arr = ['0'=>'未知'];
		$Knows = new \app\common\model\Knows(); //实例化 项目
        $KnowsList = $Knows->getKonwsListByArg(['admin_reg'=>$child_plaform,'isdelete'=>0,'status'=>1],'*'); //获取项目列表
		foreach($KnowsList as $vc){
			
			$arr[$vc['id']] = $vc['k_name'];
			
		}
        
		$this->view->assign('qbank_type',$qbank_type);
		$this->view->assign('KnowsList', $arr); 
        $Question = new \app\common\model\Questions();
        $this->view->assign('qbanktypelist', $Question->getQuestypeList()); // 题目类型
        $this->view->assign('knowslists',$KnowsList);
        $this->datalist($this->model, $map);

        return $this->view->fetch();
    }
    /**
     * 文件上传
     */
    public function uploadexcel()
    {
        $file = $this->request->file('file');
        $idsss = $this->request->param('idsss');
        var_dump($idsss);die;
        $fileinfo=$file->getInfo();
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path,$fileinfo['name']);
        $url = './tmp/uploads/' . $info->getSaveName();

        // 通过文件上传，然后取到上传后的完整路径文件名
//        $file;
        // 解析 Excel 头部信息，返回 $excelHeader = ['A' => '第一行A列描述', 'B' => '第一行B列描述', 'C' => '第一行C列描述',...]
        $excelHeader = \Excel::parseHeader($url);
//        var_dump($excelHeader);die;
        // 将 $excelHeader 数据抛给前端，让用户选择对应关系，然后再返回给后台进行对应数据的解析，例如抛给后台的数据如下isdelete selectnumber describe status level answer
        $header = ['A' => 'q_typeid', 'B' => 'q_question', 'C' => 'q_select','D' => 'q_selectnumber','E' => 'q_answer','F' => 'q_describe','G' => 'q_status','H' => 'q_level'];
        $result = \Excel::parse($url, $header,20, function ($data) {

            /**
             * 可以在此处对数据进行过滤处理，例如：
             */

            foreach ($data as &$v) {
                $v['q_qbankid']=$this->request->param('qbankid');
                $v['q_create_time']=time();
            }
            Db::name('questions')->insertAll($data);
//            $cache = new Cache();
//            $cache->set('shiti',$data,3600);//存缓存
        });

        $insert = [
            'cate'     => 3,
            'name'     => $url,
            'original' => $info->getInfo('name'),
            'domain'   => '',
            'type'     => $info->getInfo('type'),
            'size'     => $info->getInfo('size'),
            'mtime'    => time(),
        ];
        Db::name('File')->insert($insert);

        return ajax_return(['name' => $url]);
    }

    public function addExecl(){
        $controller = $this->request->controller();
        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->except(['id']);
            if (is_null($data['uploadUrl'])){
                ajax_return_error('请上传一个execl');
            }

            return ajax_return_adv('添加成功');
        } else {
            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'addexecl');
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $Question = new \app\common\model\Questions();
        $controller = $this->request->controller();

        if ($this->request->isAjax()) {
            // 更新
            $data = $this->request->post();
			
		
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }
			if(!empty($data["targs"]["q_answer0"])){
			$data["targs"]["q_answer0"] = str_ireplace(array('&lt;p&gt;','&lt;/p&gt;'),'',$data["targs"]["q_answer0"]);
			}
			$data['args']['q_question'] = strip($data['args']['q_question']);
			$data['args']['q_describe'] = strip($data['args']['q_describe']);
			$data['args']['q_select'] = strip($data['args']['q_select']);

            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }

            // 更新数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                $args = $data['args'];
                $args['q_knowsid']=substr($args['q_knowsid'],0,strrpos($args['q_knowsid'],':'));
                $targs = $data['targs'] ;
			
                $questype = $Question->getQuestypeById($args['q_typeid']);
               /* if($questype[0]['sort'])$choice = 0;
                else $choice = $questype[0]['tchoice'];*/
				$choice = $data["args"]["q_typeid"];
                $args['q_answer'] = $targs['q_answer'.$choice];
				
                if(is_array($args['q_answer']))$args['q_answer'] = implode('',$args['q_answer']);
                $args['q_create_time'] = time();

                // 使用模型更新，可以在模型中定义更高级的操作
                $model = new $modelClass();
                $ret = $model->isUpdate(true)->save($args, ['id' => $data['id']]);
            } else {
                // 简单的直接使用db更新
                Db::startTrans();
                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->where('id', $data['id'])->update($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ajax_return_adv_error($e->getMessage());
                }
            }

            return ajax_return_adv("编辑成功");
        } else {
            // 编辑
            $id = $this->request->param('id');
            if (!$id) {
                throw new HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel($controller)->find($id);
            if (!$vo) {
                throw new HttpException(404, '该记录不存在');
            }

//            $subject = Db::name('subject')->field('id,subject')->select();//获得科目列表
            $subject = $Question->subject(0);//获得科目列表

            $knows   = $Question->getQuesknowsById($vo['q_knowsid']);//根据id获得知识点

            if ($knows)$this->view->assign('konws', $knows[0]);
            $qbank   = $Question->qbank(0);//获得题库列表

            $this->view->assign('knows', $knows[0]);
            $this->view->assign('qbank', $qbank);
            $this->view->assign('subject', $subject);
            $this->view->assign('questypes', $Question->getQuestypeList());
            $this->view->assign("vo", $vo);;

            return $this->view->fetch();
        }
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $Question = new \app\common\model\Questions();
        $controller = $this->request->controller();//question
        if ($this->request->isAjax()) {

            // 插入数据
            $data = $this->request->except(['id']);
            if (empty($data['args']['q_knowsid']) || empty($data['args']['q_question'])){
                return ajax_return_adv_error('缺少数据，请重新填写');
            }
			if(!empty($data["targs"]["q_answer0"])){
				$data["targs"]["q_answer0"] = str_ireplace(array('&lt;p&gt;','&lt;/p&gt;'),'',$data["targs"]["q_answer0"]);
			}
            $data['args']['admin_reg'] = $_SESSION['think']['reg'];
			$data['args']['q_question'] = strip($data['args']['q_question']);
			$data['args']['q_describe'] = strip($data['args']['q_describe']);
			$data['args']['q_select'] = strip($data['args']['q_select']);
		
            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }
            // 写入数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                $args = $data['args'];
                $args['q_knowsid']=substr($args['q_knowsid'],0,strrpos($args['q_knowsid'],':'));
                $targs = $data['targs'] ;
                $questype = $Question->getQuestypeById($args['q_typeid']);
                if($questype[0]['sort'])$choice = 0;
                else $choice = $questype[0]['tchoice'];
                $args['q_answer'] = $targs['q_answer'.$choice];
                if(is_array($args['q_answer']))$args['q_answer'] = implode('',$args['q_answer']);
//                    $page = $this->ev->get('page');
                $args['q_create_time'] = time();
                //使用模型写入，可以在模型中定义更高级的操作
                $model = new $modelClass();
                $ret = $model->isUpdate(false)->save($args);
            } else {
                // 简单的直接使用db写入
                Db::startTrans();
                try {
//                    $args['questionusername'] = $this->_user['sessionusername'];
                    $model = Db::name($this->parseTable($controller));
//                    var_dump($controller);die;
                    $ret = $model->insert($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajax_return_adv_error($e->getMessage());
                }
            }
            return ajax_return_adv('添加成功');
        } else {

            $subject =$Question->subject(0);//获得科目列表
            $qbank = $Question->qbank(0);//获得科目列表
            $this->view->assign('qbank', $qbank);
            $this->view->assign('subject', $subject);
            $this->view->assign('questypes', $Question->getQuestypeList());
            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

    /**
     * 获得章节 ajax
     */
    public function section(){
        //$child_plaform = getChildAdminRegByPlaformId($this->plaform);
		$child_plaform = $_SESSION["think"]["reg"];
        $arr=Db::name('sections')->field('id,se_name')->where('se_subjectid', $_POST['pid'])->where(['admin_reg'=>$child_plaform,'isdelete'=>0,'status'=>1])->select();
        $arr=json_encode($arr);
        return ajax_return($arr);
    }
    /**
     * 获得知识点
     */
    public function knows(){
       // $child_plaform = getChildAdminRegByPlaformId($this->plaform);
	   $child_plaform = $_SESSION["think"]["reg"];
        $arr=Db::name('knows')->field('id,k_name')->where('k_sectionid', $_POST['pid'])->where(['admin_reg'=>$child_plaform,'isdelete'=>0,'k_status'=>1])->select();
        $arr=json_encode($arr);
        return ajax_return($arr);
    }

    /**
     * 添加
     * @return mixed
     */
    public function addcsv()
    {
        $Question = new \app\common\model\Questions();
        $controller = $this->request->controller();
        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->except(['id']);
            // 验证
            if (class_exists($validateClass = Loader::parseClass(Config::get('app.validate_path'), 'validate', $controller))) {
                $validate = new $validateClass();
                if (!$validate->check($data)) {
                    return ajax_return_adv_error($validate->getError());
                }
            }
            // 写入数据
            if (
                class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $this->parseCamelCase($controller)))
                || class_exists($modelClass = Loader::parseClass(Config::get('app.model_path'), 'model', $controller))
            ) {
                //使用模型写入，可以在模型中定义更高级的操作
                $model = new $modelClass();
                $ret = $model->isUpdate(false)->save($data);
            } else {
                // 简单的直接使用db写入
                Db::startTrans();
                try {
                    $model = Db::name($this->parseTable($controller));
                    $ret = $model->insert($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajax_return_adv_error($e->getMessage());
                }
            }
            return ajax_return_adv('添加成功');
        } else {
            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'addcsv');
        }
    }
    
     
    /* 彻底清空或者删除题库中的所有试题 */

    public function clearQbankQuestion() {
        $bankId = $this->request->param('bankid');
        $bankType = $this->request->param('btype');
        $knowsid = $this->request->param('knowstypeId'); // 知识点id
        $qbankid = $this->request->param('qbankid'); // 题型id
        $getq_status = $this->request->param('getq_status'); // 是否启用
        $likename = $this->request->param('likename'); //like 试题name
        $deletetype = $this->request->param('deletetype'); // 值等于1清空当前赛选试题 不等于1清空所有
        
        $id = $this->request->param('id');
        if(empty($id)&&empty($bankId)) return ajax_return_adv("非法操作!");
        $parentid = Db::name('qbank')->where(['id'=>$bankId])->field('parentid')->find();
        if($parentid['parentid']>0){
            $tab = 'question_db';
        }else{
            $tab = 'questions';
        }

        $whereSql = array();
        if(!empty($bankId)) $whereSql['q_qbankid'] = $bankId;
        if(!empty($id)) $whereSql['id'] = array('in' , $id);
        // deletetype 为1清空筛选项 没有deltetype值清空所有试题
        try {
            if($deletetype==1){
                if(!empty($qbankid)) $whereSql['q_typeid'] = $qbankid;
                if(!empty($knowsid)) $whereSql['q_knowsid'] = $knowsid;
                if(!empty($getq_status)) $whereSql['q_status'] = $getq_status;
                if(!empty($likename)) $whereSql['q_question'] = ["like", "%" .$likename. "%"]; 
                
                if($result = Db::name($tab)->where($whereSql)->delete()) $model =  $this->getModel('Qbank')->where('id',$bankId)->setDec('total', $result);
                $success = !empty($id) ? "删除对应试题成功!" : "清空当前选中试题成功!";
                $error = !empty($id) ? "删除对应试题失败!" : "清空当前选中试题失败!";
                $msg = $result>0 ? $success : $error;
                return ajax_return_adv($msg);
            }else{
                if($result = Db::name($tab)->where($whereSql)->delete()) $model =  $this->getModel('Qbank')->where('id',$bankId)->setField('total', 0);
                $success = !empty($id) ? "删除对应试题成功!" : "清空题库试题成功!";
                $error = !empty($id) ? "删除对应试题失败!" : "清空题库试题失败!";
                $msg = $result>0 ? $success : $error;
                return ajax_return_adv($msg);
            }
        } catch (Exception $e) {
            return ajax_return_adv("操作失败！");
        }

    }

    /*回收站管理*/
    public function recyclebin(){
        $this::$isdelete = 1;
        $origin = $_SERVER['REQUEST_URI'];
        $min = stripos($origin,'.');
        if($min>1){
            $origin = substr($origin,0,$min).'.html';
        }
        $origin = str_replace('recyclebin','index',$origin);
        $this->view->assign("origin", $origin);
        return $this->index();
    }

    /**
     * 默认删除操作
     */
    public function delete()
    {
 
        $id = $this->request->param('id');
        $bankId = $this->request->param('bankid');
        if(!empty($bankId)){
			$whereSql['q_qbankid'] = $bankId;
			$num = Db::name('qbank')->field('total')->where(['id'=>$bankId])->find();
			$total = $num['total']-1;
			Db::name('qbank')->where(['id'=>$bankId])->update(['total'=>$total]);
		}
        if(!empty($id)) $whereSql['id'] = array('in' , $id);

        $result = $this->model->where($whereSql)->update(['isdelete'=>1]);
        $msg = $result ? '移动到回收站成功':'移动到回收站失败';
        return ajax_return_adv($msg);
    }

    /**
     * 从回收站恢复
     */
    public function recycle()
    {
        $id = $this->request->param('id');
        $bankId = $this->request->param('bankid');
        if(!empty($bankId)) $whereSql['q_qbankid'] = $bankId;
        if(!empty($id)) $whereSql['id'] = array('in' , $id);
        $result = $this->model->where($whereSql)->setField('isdelete',0);
        $msg = $result >0 ? '恢复成功':'恢复失败';
        return ajax_return_adv($msg);
    }

    /**
     * 从回收站彻底删除
     */
    public function deleteforever()
    {
        $id = $this->request->param('id');
        $bankId = $this->request->param('bankid');
        if(!empty($bankId)) $whereSql['q_qbankid'] = $bankId;
        if(!empty($id)) $whereSql['id'] = array('in' , $id);
        if($result = $this->model->where($whereSql)->delete()) $model =  $this->getModel('Qbank')->where('id',$bankId)->setDec('total', $result);
        $msg = $result >0 ? '彻底删除成功':'彻底删除失败';
        return ajax_return_adv($msg);
    }

     /**
     * 从回收站彻底删除
     */
    public function clear()
    {
        $bankId = $this->request->param('bankid');
        if(!empty($bankId)) $whereSql['q_qbankid'] = $bankId;
        $whereSql['isdelete'] = 1;
        $result = $this->model->where($whereSql)->delete();
        $msg = $result >=0 ? '清空回收站成功':'清空回收站失败';
        return ajax_return_adv($msg);
    }

    

    /**
     * 禁用状态
     */
    public function forbid()
    {
        $id = $this->request->param('id');
        $bankId = $this->request->param('bankid');
        if(!empty($bankId)) $whereSql['q_qbankid'] = $bankId;
        if(!empty($id)) $whereSql['id'] = array('in' , $id);
        // var_dump($this->model);exit;
        $result = Db::name('questions')->where($whereSql)->update(['status'=>0]);
        $msg = $result  ? '禁用成功':'禁用失败';
        // var_dump($msg);exit;
        return ajax_return($result,$msg);
    }

    /**
     * 禁用状态
     */
    public function reforbid()
    {
        $id = $this->request->param('id');
        $bankId = $this->request->param('bankid');
        if(!empty($bankId)) $whereSql['q_qbankid'] = $bankId;
        if(!empty($id)) $whereSql['id'] = array('in' , $id);
        // var_dump($this->model);exit;
        $result = Db::name('questions')->where($whereSql)->update(['status'=>1]);
        $msg = $result  ? '恢复成功':'恢复失败';
        // var_dump($msg);exit;
        return ajax_return($result,$msg);
    }

      /**
     * 从恢复状态
     */
    public function resume()
    {
        $bankId = $this->request->param('bankid');
        if(!empty($bankId)) $whereSql['q_qbankid'] = $bankId;
        $whereSql['isdelete'] = 1;
        $result = $this->model->where($whereSql)->setField('status',1);
        $msg = $result >=0 ? '恢复成功':'恢复失败';
        return ajax_return($result,$msg);
    }
}
